package cn.zhentao.service;

import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.MinioException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

/**
 * MinIO文件上传服务
 * 
 * @author zhentao
 */
@Service
@Slf4j
public class MinioFileService {
    
    @Value("${minio.endpoint:http://118.31.228.119:19000}")
    private String endpoint;
    
    @Value("${minio.access-key:minioadmin}")
    private String accessKey;
    
    @Value("${minio.secret-key:minioadmin}")
    private String secretKey;
    
    @Value("${minio.bucket-name:test}")
    private String bucketName;
    
    @Value("${file.url:http://118.31.228.119:19000/test/}")
    private String fileBaseUrl;
    
    private MinioClient minioClient;
    
    /**
     * 获取MinIO客户端
     */
    private MinioClient getMinioClient() {
        if (minioClient == null) {
            minioClient = MinioClient.builder()
                    .endpoint(endpoint)
                    .credentials(accessKey, secretKey)
                    .build();
        }
        return minioClient;
    }
    
    /**
     * 上传图片文件到MinIO
     */
    public String uploadQuestionImage(MultipartFile file) {
        try {
            // 生成文件名
            String originalFilename = file.getOriginalFilename();
            String extension = originalFilename != null && originalFilename.contains(".") 
                ? originalFilename.substring(originalFilename.lastIndexOf(".")) 
                : ".jpg";
            
            String dateFolder = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
            String fileName = "questions/" + dateFolder + "/" + UUID.randomUUID().toString() + extension;
            
            // 上传文件
            MinioClient client = getMinioClient();
            client.putObject(
                PutObjectArgs.builder()
                    .bucket(bucketName)
                    .object(fileName)
                    .stream(file.getInputStream(), file.getSize(), -1)
                    .contentType(file.getContentType())
                    .build()
            );
            
            // 返回文件URL
            String fileUrl = fileBaseUrl + fileName;
            log.info("📁 文件上传成功: {}", fileUrl);
            return fileUrl;
            
        } catch (MinioException | IOException | InvalidKeyException | NoSuchAlgorithmException e) {
            log.error("📁 文件上传失败", e);
            return null;
        }
    }
    
    /**
     * 检查MinIO连接状态
     */
    public boolean checkConnection() {
        try {
            MinioClient client = getMinioClient();
            // 尝试列出存储桶来测试连接
            client.listBuckets();
            return true;
        } catch (Exception e) {
            log.error("MinIO连接检查失败", e);
            return false;
        }
    }
}
